package priv.dajie.tzzq.spider.dota.steam;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import priv.dajie.tzzq.bot.BotManager;
import priv.dajie.tzzq.bot.steam.SteamUser;
import priv.dajie.tzzq.common.ApplicationContextUnit;
import priv.dajie.tzzq.model.QualityName;
import priv.dajie.tzzq.service.SteamService;
import priv.dajie.tzzq.spider.Base.DotaSpider;
import priv.dajie.tzzq.spider.model.*;
import priv.dajie.tzzq.common.Tools;

import java.net.URISyntaxException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SteamDotaSpider implements DotaSpider,Runnable {

    private SpiderInfo spiderInfo;
    private SteamUser steamUser;
    private Logger logger = LogManager.getLogger(this.getClass());
    private SteamService steamService = (SteamService) ApplicationContextUnit.getInstance().getBean("steamService");

    public SteamDotaSpider(){
        steamUser = BotManager.getSteamBot().getSteamUser();
    }

    public SteamDotaSpider(SpiderInfo spiderInfo) {
        this.spiderInfo = spiderInfo;
        this.steamUser = BotManager.getSteamBot().getSteamUser();
    }

    public SteamDotaSpider(SpiderInfo spiderInfo, SteamUser steamUser){
        this.spiderInfo = spiderInfo;
        this.steamUser = steamUser;
    }


    @Override
    public List getItem(String hero, String type,String rarity) { // 待添加页面循环 2019.7.18
        int start = 0;
        int count = 100;
        int max = 1;
        String heroCN;
        if (type == null) {
            heroCN = spiderInfo.getHeroCN(hero);
            type = "any";
            hero = "tag_" + hero;
        } else {
            heroCN = spiderInfo.getTypeCN(type);
            type = "tag_" + type;
            hero = "any";
        }
        while (start<max) {
            String rarityCN = spiderInfo.getRarityCN(rarity);
            URIBuilder uriBuilder;
            int n=1;
            try {
                uriBuilder = new URIBuilder("https://steamcommunity.com/market/search/render/");
                uriBuilder.setParameter("category_570_Hero[]", hero);
                uriBuilder.setParameter("category_570_Rarity[]", "tag_" + rarity);
                uriBuilder.setParameter("category_570_Slot[]", "any");
                uriBuilder.setParameter("category_570_Type[]", type);
                uriBuilder.setParameter("appid", "570");
                uriBuilder.setParameter("start", start + "");
                uriBuilder.setParameter("count", count + "");
                uriBuilder.setParameter("sort_dir", "desc");
                uriBuilder.setParameter("norender", "1");
                uriBuilder.setParameter("search_descriptions", "0");
                uriBuilder.setParameter("sort_column", "popular");
                HttpGet httpGet = new HttpGet(uriBuilder.build());
                String jsonStr = steamUser.open(httpGet, true);
                logger.debug(httpGet);
                JSONObject json = JSON.parseObject(jsonStr);

                if (json == null || !json.getBoolean("success")) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    logger.warn("返回内容错误：" + httpGet + "\n"+jsonStr);
                    try {
                        Thread.sleep(1000 * n++);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }
                n=1;
                max = json.getInteger("total_count");
                JSONArray results = json.getJSONArray("results");
                for (int i = 0; i < results.size(); i++) {
                    JSONObject result = results.getJSONObject(i);
                    String name = result.getString("name");
                    QualityName qualityName = Tools.getQualityName(name);
                    String steamName = result.getString("hash_name");
                    int num = result.getInteger("sell_listings");
                    double price = result.getDouble("sell_price")/100;
//                    String nameID = null;
//                    ItemInfo dbInfo = steamTable.getItemInfoBySteamName(steamName); // 如果存在则查找nameid；
//                    if (dbInfo.getId() == null) {
//                        nameID = getNameID(steamName);
//                    }
                    ItemInfo itemInfo = new ItemInfo(null, qualityName, rarityCN, heroCN, steamName, Platform.STEAM);
                    SellingInfo sellingInfo = new SellingInfo(itemInfo, price, num, TradeType.SELL);
                    steamService.addItem(sellingInfo);
                }

                start+=count;
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

        }

        return null;
    }

    public String getNameID(String steamName){

        HttpGet httpGet = new HttpGet("https://steamcommunity.com/market/listings/570/" + steamName.replace(" ","%20")+"/");
        String html = steamUser.open(httpGet, true);
//        System.out.println(httpGet);
        String nameID = null;
        Pattern pattern = Pattern.compile("Market_LoadOrderSpread\\( (.*) \\)");
        Matcher matcher = pattern.matcher(html);
        if(matcher.find()){
            nameID = matcher.group(1);
        }
        return nameID;
    }

    @Override
    public void startSpider() {
        while(spiderInfo.getSize()>0) {
            InfoElement infoElement = spiderInfo.getInfoElement();
            logger.info("剩余:"+spiderInfo.getSize()+" | "+infoElement);
            if (infoElement.getElementType() == ElementType.HERO) {
                for (String rarity : spiderInfo.getRarity().keySet())
                    getItem(infoElement.getName(), null, rarity);
            }
        }
    }

    @Override
    public void setSpiderInfo(SpiderInfo spiderInfo) {
        this.spiderInfo = spiderInfo;
    }


    @Override
    public void run() {
        startSpider();
    }

    public static void main(String[] args) {
        new SteamDotaSpider(SteamInfos.getSteamInfos()).startSpider();

    }

}
